package com.momin.gmall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.momin.common.utils.PageUtils;
import com.momin.common.utils.Query;

import com.momin.gmall.product.dao.CategoryDao;
import com.momin.gmall.product.entity.CategoryEntity;
import com.momin.gmall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //一级分类
        List<CategoryEntity> levelMenu = categoryEntities.stream().filter(categoryEntity ->
            categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,categoryEntities));
            return menu; 
        }).sorted((menu1,menu2)->{
           return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return levelMenu;
    }

    @Override
    public void removeMenuByIds(List<Long> ids) {
        //TODO 1、检查当前菜单是否被其他地方应用
        //逻辑删除
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public List<Long> queryCategoryPath(Long catId) {
        ArrayList<Long> list = new ArrayList<>();
        getCategoryPath(catId,list);
        return list;
    }

    private void getCategoryPath(Long catId,List<Long> list){
        CategoryEntity categoryEntity = baseMapper.selectById(catId);
        list.add(categoryEntity.getCatId());
        if(categoryEntity.getParentCid()!=0){
            getCategoryPath(categoryEntity.getParentCid(),list);
        }
    }


    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all) {
        List<CategoryEntity> list =
                all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId()
        ).map((categoryEntity) -> {//递归查询子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return list;
    }

}